plotly

Plotly’s R graphing library makes interactive, publication-quality graphs. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, and 3D (WebGL based) charts.

pie chart

col <- "color"     # enter string that include na# skimr::skim(diamonds$color)
df_graph <- diamonds # dataframeme of col

df_graph <- as.data.frame(table(df_graph[,col]))
fig <- plot_ly(df_graph, labels = ~Var1, values = ~Freq, type = 'pie')
fig <- fig %>% layout(title = 'colors',
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

fig

Bubble Chart

data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")

fig <- plot_ly(data, x = ~Women, y = ~Men, text = ~School, type = 'scatter', mode = 'markers',
        marker = list(size = ~Gap, opacity = 0.5))
fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
         xaxis = list(showgrid = FALSE),
         yaxis = list(showgrid = FALSE))

fig

Bar Chart

fig <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(20, 14, 23),
  name = "SF Zoo",
  type = "bar"
)

fig

Line and Points Plot

library(plotly)

trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)

data <- data.frame(x, trace_0, trace_1, trace_2)

fig <- plot_ly(data, x = ~x, y = ~trace_0, name = 'trace 0', type = 'scatter', mode = 'lines') 
fig <- fig %>% add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines+markers') 
fig <- fig %>% add_trace(y = ~trace_2, name = 'trace 2', mode = 'markers')

fig

Boxplot

fig <- plot_ly(y = list(1,2,3,4,5), type = "box", quartilemethod="linear", name="Linear Quartile Mode")
fig <- fig %>% add_trace(y = list(1,2,3,4,5), quartilemethod="inclusive", name="Inclusive Quartile Mode")
fig <- fig %>% add_trace(y = list(1,2,3,4,5), quartilemethod="exclusive", name="Exclusive Quartile Mode")
fig <- fig %>% layout(title = "Modifying The Algorithm For Computing Quartiles")

fig
library(quantmod)
getSymbols("AAPL",src='yahoo')
## [1] "AAPL"
# basic example of ohlc charts
df <- data.frame(Date=index(AAPL),coredata(AAPL))
df <- tail(df, 30)

# cutom colors
i <- list(line = list(color = '#FFD700'))
d <- list(line = list(color = '#0000ff'))

fig <- df %>% plot_ly(x = ~Date, type="candlestick",
          open = ~AAPL.Open, close = ~AAPL.Close,
          high = ~AAPL.High, low = ~AAPL.Low,
          increasing = i, decreasing = d)

fig

scatter-plots-on-maps

library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')

# geo styling
g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showland = TRUE,
  landcolor = toRGB("gray95"),
  subunitcolor = toRGB("gray85"),
  countrycolor = toRGB("gray85"),
  countrywidth = 0.5,
  subunitwidth = 0.5
)

fig <- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
    text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
    color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
  )
fig <- fig %>% colorbar(title = "Incoming flights<br />February 2011")
fig <- fig %>% layout(
    title = 'Most trafficked US airports<br />(Hover for airport)', geo = g
  )

fig

PCA Visualization in R

library(plotly)
library(stats)
data(iris)
X <- subset(iris, select = -c(Species))
prin_comp <- prcomp(X, rank. = 2)
components <- prin_comp[["x"]]
components <- data.frame(components)
components <- cbind(components, iris$Species)
components$PC2 <- -components$PC2

fig <- plot_ly(components, x = ~PC1, y = ~PC2, color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96'), type = 'scatter', mode = 'markers')%>%
  layout(
    legend=list(title=list(text='color')),
    plot_bgcolor='#e5ecf6',
    xaxis = list(
      title = "0",
      zerolinecolor = "#ffff",
      zerolinewidth = 2,
      gridcolor='#ffff'),
    yaxis = list(
      title = "1",
      zerolinecolor = "#ffff",
      zerolinewidth = 2,
      gridcolor='#ffff'))
fig

Maxed Subplots

library(plotly)

# read in Walmart data
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/1962_2006_walmart_store_openings.csv")


# first plot - bar chart
total <- plyr::count(df$YEAR)
fit <- fitted(loess(total$freq ~ total$x))

fig2 <- plot_ly(data = total, x = ~x, y = ~freq, type = "bar", showlegend=FALSE,
              marker=list(color=~x, showscale=FALSE)) 
fig2 <- fig2 %>% add_lines(y = fit, showlegend=FALSE, color = 'black') 
fig2 <- fig2 %>% layout(showlegend=FALSE, xaxis = list(side="right", showgrid=FALSE),
         yaxis=list(showgrid=FALSE))


# second plot - scattergeo map
g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showlakes = TRUE,
  lakecolor = toRGB('white'))

fig3 <- plot_geo(df, lat = ~LAT, lon = ~LON) 
fig3 <- fig3 %>% add_markers(
    text = ~OPENDATE, showlegend=FALSE,
    marker=list(color = ~YEAR, showscale=FALSE),
    hoverinfo = "text") 
fig3 <- fig3 %>% layout(geo = g, showlegend=FALSE)




# subplot
fig <- subplot(fig2, fig3, nrows = 2) 
fig <- fig %>% layout(title = "Walmart Store Openings by Year",
         xaxis = list(domain=list(x=c(0,0.5),y=c(0,0.5))),
         scene = list(domain=list(x=c(0.5,1),y=c(0,0.5))),
         xaxis2 = list(domain=list(x=c(0.5,1),y=c(0.5,1))),
         showlegend=FALSE,showlegend2=FALSE)

fig

ADD customs Control

library(plotly)
library(quantmod)

d <- quantmod::getSymbols("AAPL")

df <- data.frame(Date=index(AAPL),coredata(AAPL))

high_annotations <- list(
  x=df$Date[df$AAPL.High == max(df$AAPL.High)], 
  y=max(df$AAPL.High),
  xref='x', yref='y',
  text=paste0('High: $',max(df$AAPL.High)),
  ax=0, ay=-40
)

low_annotations <- list(
  x=df$Date[df$AAPL.Low == min(df$AAPL.Low)], 
  y=min(df$AAPL.Low),
  xref='x', yref='y',
  text=paste0('Low: $',min(df$AAPL.Low)),
  ax=0, ay=40
)

# updatemenus component
updatemenus <- list(
  list(
    active = -1,
    type= 'buttons',
    buttons = list(
      list(
        label = "High",
        method = "update",
        args = list(list(visible = c(FALSE, TRUE)),
                    list(title = "Apple High",
                         annotations = list(c(), high_annotations)))),
      list(
        label = "Low",
        method = "update",
        args = list(list(visible = c(TRUE, FALSE)),
                    list(title = "Apple Low",
                         annotations = list(low_annotations, c() )))),
      list(
        label = "Both",
        method = "update",
        args = list(list(visible = c(TRUE, TRUE)),
                    list(title = "Apple",
                         annotations = list(low_annotations, high_annotations)))),
      list(
        label = "Reset",
        method = "update",
        args = list(list(visible = c(TRUE, TRUE)),
                    list(title = "Apple",
                         annotations = list(c(), c())))))
  )
)

fig <- df %>% plot_ly(type = 'scatter', mode = 'lines') 
fig <- fig %>% add_lines(x=~Date, y=~AAPL.High, name="High",
            line=list(color="#33CFA5")) 
fig <- fig %>% add_lines(x=~Date, y=~AAPL.Low, name="Low",
            line=list(color="#F06A6A")) 
fig <- fig %>% layout(title = "Apple", showlegend=FALSE,
         xaxis=list(title="Date"),
         yaxis=list(title="Price ($)"),
         updatemenus=updatemenus)


fig

Range Sliders and selectors

getSymbols(Symbols = c("AAPL", "MSFT"), from = '2018-01-01', to = '2019-01-01')
## [1] "AAPL" "MSFT"
ds <- data.frame(Date = index(AAPL), AAPL[,6], MSFT[,6])

fig <- plot_ly(ds, x = ~Date)
fig <- fig %>% add_lines(y = ~AAPL.Adjusted, name = "Apple")
fig <- fig %>% add_lines(y = ~MSFT.Adjusted, name = "Microsoft")
fig <- fig %>% layout(
    title = "Stock Prices",
    xaxis = list(
      rangeselector = list(
        buttons = list(
          list(
            count = 3,
            label = "3 mo",
            step = "month",
            stepmode = "backward"),
          list(
            count = 6,
            label = "6 mo",
            step = "month",
            stepmode = "backward"),
          list(
            count = 1,
            label = "1 yr",
            step = "year",
            stepmode = "backward"),
          list(
            count = 1,
            label = "YTD",
            step = "year",
            stepmode = "todate"),
          list(step = "all"))),

      rangeslider = list(type = "date")),

    yaxis = list(title = "Price"))

fig

Slider

library(plotly)

x <- seq(0,10, length.out = 1000)

# create data
aval <- list()
for(step in 1:11){
  aval[[step]] <-list(visible = FALSE,
                      name = paste0('v = ', step),
                      x=x,
                      y=sin(step*x))
}
aval[3][[1]]$visible = TRUE

# create steps and plot all traces
steps <- list()
fig <- plot_ly()
for (i in 1:11) {
 fig <- add_lines(fig,x=aval[i][[1]]$x,  y=aval[i][[1]]$y, visible = aval[i][[1]]$visible, 
                 name = aval[i][[1]]$name, type = 'scatter', mode = 'lines', hoverinfo = 'name', 
                 line=list(color='00CED1'), showlegend = FALSE)

  step <- list(args = list('visible', rep(FALSE, length(aval))),
               method = 'restyle')
  step$args[[2]][i] = TRUE  
  steps[[i]] = step 
}  

# add slider control to plot
fig <- fig %>%
  layout(sliders = list(list(active = 3,
                             currentvalue = list(prefix = "Frequency: "),
                             steps = steps)))

fig